import requests
from beautifultable import BeautifulTable
import pandas as pd

# 用get方法访问服务器并提取页面数据
def getHtml(cmd, page):
    # 构建完整的URL
    url = f"https://push2.eastmoney.com/api/qt/clist/get?fid=f3&po=1&pz=20&pn={page}&fs={cmd}&fields=f12,f13,f14,f1,f2,f4,f3,f152,f5,f6,f7,f15,f18,f16,f17,f10,f8,f9,f23"

    # 简化headers，移除可能包含中文的字段
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        'Accept': 'application/json, text/plain, */*',
        'Connection': 'keep-alive',
        'Host': 'push2.eastmoney.com',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-site',
    }

    # 简化cookies
    cookies = {
        'qgqp_b_id': '17a61503fd887741a519997ccdd24033',
        'st_pvi': '46223553544940',
        'st_si': '70041422244381',
    }

    try:
        r = requests.get(url, headers=headers, cookies=cookies, timeout=10)
        r.raise_for_status()
        data = r.json()
        return data
    except Exception as e:
        print(f"请求失败: {e}")
        return None


# 获取单个页面股票数据
def getOnePageStock(cmd, page):
    data = getHtml(cmd, page)

    if data is None or data.get('rc') != 0:
        print(f"获取数据失败，页码: {page}")
        return []

    # 直接返回原始的股票字典数据，不要转换成列表
    stock_list = data.get('data', {}).get('diff', [])
    return list(stock_list.values())  # 直接返回字典列表

def process_data_stock(data):
    stocks = []
    for stock in data:
        stocks.append([
            stock.get("f12", ""),  # 0-代码
            stock.get("f14", ""),  # 1-名称
            f"{stock.get('f2', 0) / 100:.2f}" if stock.get("f2") else "-",  # 2-最新价
            f"{stock.get('f3', 0) / 100:.2f}%" if stock.get("f3") else "-",  # 3-涨跌幅
            f"{stock.get('f4', 0) / 100:.2f}" if stock.get("f4") else "-",  # 4-涨跌额
            str(stock.get("f5", "")),  # 5-成交量
            f"{int(stock.get('f6', 0)) / 1000000:.1f}万" if stock.get("f6") else "-",  # 6-成交额
            f"{stock.get('f7', 0) / 100:.2f}%" if stock.get("f7") else "-"  # 7-涨幅
    ])
    return stocks


def show_stocks(stocks, plate_name):
    """使用BeautifulTable显示股票数据"""
    if not stocks:
        return

    print(f"\n🎯 【{plate_name}】股票列表（共{len(stocks)}只）")
    print("=" * 120)

    table = BeautifulTable()
    table.set_style(BeautifulTable.STYLE_COMPACT)
    table.columns.header = ["序号", "代码", "名称", "最新价", "涨跌幅", "涨跌额", "成交量", "成交额", "振幅"]
    table.columns.alignment = BeautifulTable.ALIGN_CENTER
    table.columns.width = [6, 8, 12, 8, 8, 12, 12, 12, 12]
    data = process_data_stock(stocks)
    for i, stock in enumerate(data, 1):
        table.rows.append([i, stock[0], stock[1], stock[2], stock[3], stock[4], stock[5],stock[6], stock[7]])
    print(table)
    print()
def save_to_excel(stocks, plate):
    if not stocks:
        print(f"❌ 【{plate}】无数据可保存")
        return
    data = process_data_stock(stocks)
    # 创建DataFrame
    df = pd.DataFrame(data, columns=[
        "代码", "名称", "最新价", "涨跌幅", "涨跌额",
        "成交量", "成交额", "涨幅"
    ])

    # 保存为Excel文件
    filename = f"stock_data/{plate}.xlsx"
    try:
        df.to_excel(filename, index=False)
        print(f"💾 【{plate}】数据已保存到: {filename}")
        return filename
    except Exception as e:
        print(f"❌ 【{plate}】保存Excel失败: {e}")
        return None



def main():
    cmd = {
        "沪深A股": "m:0+t:6,m:0+t:80,m:1+t:2",
        "创业板": "m:0+t:80+f:!2"
    }
    for market_name, market_code in cmd.items():
        print(f"正在获取{market_name}数据...")
        all_stocks = []
        page = 1
        while page <= 5:
            print(f"正在获取第{page}页...")
            stocks = getOnePageStock(market_code, page)
            all_stocks.extend(stocks)
            page = page + 1
        show_stocks(all_stocks, market_name)
        save_to_excel(all_stocks, market_name)
if __name__ == "__main__":
    main()